package com.example.imtoken.core.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.imtoken.R
import com.xuexiang.xui.utils.StatusBarUtils
import com.xuexiang.xui.utils.WidgetUtils
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog

abstract class BaseActivity<T : BaseViewModel, BD : ViewDataBinding>(private val clz: Class<T>) :
    AppCompatActivity() {

    protected val viewModel by lazy {
        ViewModelProvider(this).get(clz)
    }

    protected lateinit var dataBinding: BD

    private var mLoadingDialog: MiniLoadingDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        dataBinding = DataBindingUtil.setContentView(this, initLayoutId())
        initBar(true, R.color.barBomColor)
//        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

        mLoadingDialog =
            WidgetUtils.getMiniLoadingDialog(this, resources.getString(R.string.pleaseWait))
        mLoadingDialog?.window?.setBackgroundDrawableResource(R.color.black)
        mLoadingDialog?.setCancelable(true)

        init()
        initObserves()
    }

    fun getViewModelFactory(factory: ViewModelProvider.Factory): T {
        return ViewModelProvider(this, factory).get(clz)
    }

    abstract fun initLayoutId(): Int
    abstract fun init()

    private fun initObserves() {
        viewModel.mDialog.observe(this) {
            if (it) {
                mLoadingDialog?.show()
            } else {
                mLoadingDialog?.dismiss()
            }
        }
        viewModel.mErrorStr.observe(this) {
            ToastUtils.showShort(it)
        }
        viewModel.mErrorResId.observe(this) {
            ToastUtils.showShort(it)
        }
    }

    protected fun hideInput() {
        if (KeyboardUtils.isSoftInputVisible(this)) {
            KeyboardUtils.hideSoftInput(this)
        }
    }

    //初始化任务栏
    protected fun initBar(isAddBar: Boolean = false, sColor: Int = android.R.color.transparent) {
        if (isAddBar) {
            BarUtils.addMarginTopEqualStatusBarHeight(dataBinding.root)
            BarUtils.setStatusBarColor(
                this,
                ContextCompat.getColor(this, sColor)
            )
        } else {
            BarUtils.subtractMarginTopEqualStatusBarHeight(dataBinding.root)
            BarUtils.setStatusBarColor(
                this,
                ContextCompat.getColor(this, sColor)
            )
        }
        StatusBarUtils.setStatusBarLightMode(this)
    }
}